﻿using Business.Service;
using Model;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Transactions;
using System.Web;
using System.Web.Mvc;

namespace MvcAppWeb.Controllers
{
    public class LocationGoodsController : BaseDataController
    {
        //
        // GET: /LocationGoods/

        public ActionResult LocationGoods()
        {
            if (Session["UserInfo"] == null) return RedirectToAction("LogOn", "Account");
            else
            {
                AppUserList model = (AppUserList)Session["UserInfo"];
                return View(model);

            }
        }

        /// <summary>
        /// 初始化数据
        /// </summary>
        /// <param name="locationCode"></param>
        /// <param name="goodsCode"></param>
        /// <param name="goodsName"></param>
        /// <param name="valid"></param>
        /// <returns></returns>
        public JsonResult InitJsonResult(string locationCode, string goodsCode, string goodsName, string valid)
        {
            int page = int.Parse(Request["page"].ToString());
            int rows = int.Parse(Request["rows"].ToString());
            int total = 0;
            string where = " where 1=1 and lo.STATUS=1 ";
            if (!string.IsNullOrEmpty(locationCode))
            {
                where += " and lo.LOCATIONCODE like'%" + locationCode + "%'";
            }
            if (!string.IsNullOrEmpty(goodsCode))
            {
                where += " and g.GOODSCODE like'%" + goodsCode + "%'";
            }

            if (!string.IsNullOrEmpty(goodsName))
            {
                where += " and g.GOODSNAME like'%" + goodsName + "%'";
            }
            if (!string.IsNullOrEmpty(valid))
            {
                where += " and L.STATUS =" + valid + "";
            }

            var retData = new object();
            BLocationGoods li = new BLocationGoods();
            retData = li.GetLocationGoodsList(page, rows, out total, where).ToList();
            Dictionary<string, object> json = new Dictionary<string, object>();
            json.Add("total", total);
            json.Add("rows", retData);
            return Json(json);
        }

        /// <summary>
        /// 获取仓库信息
        /// </summary>
        /// <returns></returns>
        public JsonResult GetWarehouseList()
        {
            string defaultValue = Request["defaultValue"].ToString();
            var retData = new object();
            BLocationInfo nbl = new BLocationInfo();
            retData = nbl.GetWarehouseList(defaultValue).ToList();
            return Json(retData);
        }


        /// <summary>
        /// 修改or新增
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string SaveData()
        {
            string sjson = string.Empty;
            try
            {
                AppUserList model = (AppUserList)Session["UserInfo"];
                LocationGoods location = new LocationGoods();

                string goodsCode = Request["txtGoodsCode"];
                string goodsID = Request["hiddenGOODSID"];
                string locationGoodsId = Request["hiddenLOCATIONGOODSID"];
                string locationId = Request["hiddenLOCATIONID"];
                string locationStatus = Request["hiddenStatus"];
                location.STATUS = Convert.ToInt32(Request["valids"]);
                location.LOCATIONCODE = Request["locationCode"];
                location.REMARK = Request["txtRemark"];


                location.CREATER = model.USERNAME;

                BLocationGoods nbl = new BLocationGoods();
                LocationInventoryInfo checklocation = nbl.CheckLocation(locationId, goodsID);
                int n = 0;

                if (location.STATUS == 0)//当要设置一个商品库位不启用的时候判断该商品是否有库存有库存则不允许弃用
                {
                    if (checklocation != null && checklocation.QTY > 0)
                    {
                        sjson = "{success:false,msg:'该商品库存数还有：" + checklocation.QTY.ToString() + ",请先清空库存！'}";
                        return sjson;
                    }
                    else
                    {
                        location.LOCATIONGOODSID = int.Parse(locationGoodsId);
                        n = nbl.UpdateLocationGoods(location);

                        ActionInfo ai = new ActionInfo();
                        if (location.STATUS == 0)
                        {
                            ai.OPERATIONNEW = "弃用";
                        }
                        else
                        {
                            ai.OPERATIONNEW = "启用";
                        }
                        BAction action = new BAction();

                        ai.ACTIONTYPECODE = 1;
                        ai.OPERATION = "修改";
                        ai.OPCONTENT = "货位关联ID:" + location.LOCATIONGOODSID.ToString() + ",货位编号:" + location.LOCATIONCODE.ToString() + ",商品编号：" + goodsCode.ToString();
                        ai.OPERATIONOLD = "";

                        ai.USERCODE = model.USERCODE;
                        action.AddLmActionInfo(ai);
                    }
                }
                else
                {
                    string where = " ";
                    if (!string.IsNullOrEmpty(location.LOCATIONCODE))
                    {
                        where += " and LOCATIONCODE ='" + location.LOCATIONCODE + "'";
                    }

                    var retData = new object();
                    BLocationInfo li = new BLocationInfo();
                    List<Location> lt = li.GetLocationCodeList("", where).ToList();
                    List<Goods> goods = nbl.CheckGoodsInfo(goodsCode).ToList();

                    string warehouseName = "";
                    if (lt.Count > 0)//判断货位是否存在
                    {
                        if (goods.Count > 0)//判断商品是否存在
                        {

                            location.LOCATIONID = lt[0].LOCATIONID;
                            location.GOODSID = goods[0].GOODSID;

                            string lgwhere = "";
                            if (lt[0].WAREHOUSEID == 709)//正常仓允许一个货位多个商品
                            {
                                if (goodsCode.IndexOf('W') > -1)
                                {
                                    lgwhere = " where t1.STATUS=1 and  t1.goodsid=" + goods[0].GOODSID + " and t2.WAREHOUSEID=709 ";
                                }
                                else
                                {
                                    lgwhere = " where t1.STATUS=1 and  t1.goodsid=" + goods[0].GOODSID;
                                }

                                warehouseName = "正常仓";
                            }
                            else if (lt[0].WAREHOUSEID == 712)//分拣仓一对一
                            {
                                if (goodsCode.IndexOf('W') > -1)
                                {
                                    warehouseName = "分拣仓";
                                    lgwhere = " where t1.STATUS=1  and t1.LOCATIONID=" + lt[0].LOCATIONID;
                                }
                                else
                                {
                                    sjson = "{success:false,msg:'非WOC商品只能放在正常仓'}";
                                    return sjson;
                                }
                            }
                            else if (lt[0].WAREHOUSEID == 713)//摘果仓一对一
                            {
                                if (goodsCode.IndexOf('W') > -1)
                                {
                                    warehouseName = "摘果仓";
                                    lgwhere = " where t1.STATUS=1  and t1.LOCATIONID=" + lt[0].LOCATIONID;
                                }
                                else
                                {
                                    sjson = "{success:false,msg:'非WOC商品只能放在正常仓'}";
                                    return sjson;
                                }
                            }

                            List<LocationGoods> lg = nbl.GetLocationGoodsInfo(lgwhere).ToList();
                            if (lg.Count < 1)//是否满足关联条件
                            {
                                if (lt[0].WAREHOUSEID == 712)//如果是增加分拣仓关联
                                {
                                    List<LocationGoods> lg1 = nbl.GetLocationGoodsInfo(" where  t1.STATUS=1 and t1.goodsid=" + goods[0].GOODSID + " and t2.WAREHOUSEID=712").ToList();
                                    if (lg1.Count < 1)//判断商品是否在分拣仓存在
                                    {
                                        if (string.IsNullOrEmpty(locationId))
                                        {
                                            n = nbl.AddLocationGoods(location);
                                            BAction action = new BAction();
                                            ActionInfo ai = new ActionInfo();
                                            ai.ACTIONTYPECODE = 1;
                                            ai.OPERATION = "新增";
                                            ai.OPCONTENT = "货位ID" + location.LOCATIONID.ToString() + ",商品ID" + location.GOODSID.ToString();
                                            ai.OPERATIONOLD = "";
                                            ai.OPERATIONNEW = "";
                                            ai.USERCODE = model.USERCODE;
                                            action.AddLmActionInfo(ai);


                                        }
                                        else
                                        {
                                            location.LOCATIONGOODSID = int.Parse(locationGoodsId);
                                            n = nbl.UpdateLocationGoods(location);

                                            ActionInfo ai = new ActionInfo();
                                            if (location.STATUS == 0)
                                            {
                                                ai.OPERATIONNEW = "弃用";
                                            }
                                            else
                                            {
                                                ai.OPERATIONNEW = "启用";
                                            }
                                            BAction action = new BAction();

                                            ai.ACTIONTYPECODE = 1;
                                            ai.OPERATION = "修改";
                                            ai.OPCONTENT = "货位关联ID:" + location.LOCATIONGOODSID.ToString() + ",货位编号:" + location.LOCATIONCODE.ToString() + ",商品编号：" + goodsCode.ToString();
                                            ai.OPERATIONOLD = "";

                                            ai.USERCODE = model.USERCODE;
                                            action.AddLmActionInfo(ai);
                                        }
                                    }
                                    else
                                    {
                                        sjson = "{success:false,msg:'" + goodsCode + "在" + warehouseName + "已存在正在使用库位！'}";
                                    }

                                }
                                else if (lt[0].WAREHOUSEID == 709)
                                {
                                    if (string.IsNullOrEmpty(locationId))
                                    {
                                        n = nbl.AddLocationGoods(location);
                                        BAction action = new BAction();
                                        ActionInfo ai = new ActionInfo();
                                        ai.ACTIONTYPECODE = 1;
                                        ai.OPERATION = "新增";
                                        ai.OPCONTENT = "货位ID" + location.LOCATIONID.ToString() + ",商品ID" + location.GOODSID.ToString();
                                        ai.OPERATIONOLD = "";
                                        ai.OPERATIONNEW = "";
                                        ai.USERCODE = model.USERCODE;
                                        action.AddLmActionInfo(ai);
                                    }
                                    else
                                    {
                                        location.LOCATIONGOODSID = int.Parse(locationGoodsId);
                                        n = nbl.UpdateLocationGoods(location);

                                        ActionInfo ai = new ActionInfo();
                                        if (location.STATUS == 0)
                                        {
                                            ai.OPERATIONNEW = "弃用";
                                        }
                                        else
                                        {
                                            ai.OPERATIONNEW = "启用";
                                        }
                                        BAction action = new BAction();

                                        ai.ACTIONTYPECODE = 1;
                                        ai.OPERATION = "修改";
                                        ai.OPCONTENT = "货位关联ID:" + location.LOCATIONGOODSID.ToString() + ",货位编号:" + location.LOCATIONCODE.ToString() + ",商品编号：" + goodsCode.ToString();
                                        ai.OPERATIONOLD = "";

                                        ai.USERCODE = model.USERCODE;
                                        action.AddLmActionInfo(ai);
                                    }
                                }
                                else if (lt[0].WAREHOUSEID == 713)//如果是增加摘果仓关联
                                {
                                    List<LocationGoods> lg2 = nbl.GetLocationGoodsInfo(" where  t1.STATUS=1 and t1.goodsid=" + goods[0].GOODSID + " and t2.WAREHOUSEID=713").ToList();
                                    if (lg2.Count < 1)//判断商品是否在摘果仓存在
                                    {
                                        if (string.IsNullOrEmpty(locationId))
                                        {
                                            n = nbl.AddLocationGoods(location);
                                            BAction action = new BAction();
                                            ActionInfo ai = new ActionInfo();
                                            ai.ACTIONTYPECODE = 1;
                                            ai.OPERATION = "新增";
                                            ai.OPCONTENT = "货位ID" + location.LOCATIONID.ToString() + ",商品ID" + location.GOODSID.ToString();
                                            ai.OPERATIONOLD = "";
                                            ai.OPERATIONNEW = "";
                                            ai.USERCODE = model.USERCODE;
                                            action.AddLmActionInfo(ai);


                                        }
                                        else
                                        {
                                            location.LOCATIONGOODSID = int.Parse(locationGoodsId);
                                            n = nbl.UpdateLocationGoods(location);

                                            ActionInfo ai = new ActionInfo();
                                            if (location.STATUS == 0)
                                            {
                                                ai.OPERATIONNEW = "弃用";
                                            }
                                            else
                                            {
                                                ai.OPERATIONNEW = "启用";
                                            }
                                            BAction action = new BAction();

                                            ai.ACTIONTYPECODE = 1;
                                            ai.OPERATION = "修改";
                                            ai.OPCONTENT = "货位关联ID:" + location.LOCATIONGOODSID.ToString() + ",货位编号:" + location.LOCATIONCODE.ToString() + ",商品编号：" + goodsCode.ToString();
                                            ai.OPERATIONOLD = "";

                                            ai.USERCODE = model.USERCODE;
                                            action.AddLmActionInfo(ai);
                                        }
                                    }
                                    else
                                    {
                                        sjson = "{success:false,msg:'" + goodsCode + "在" + warehouseName + "已存在正在使用库位！'}";
                                    }

                                }
                            }
                            else//修改
                            {
                                if (locationStatus == "1" && !string.IsNullOrEmpty(locationId))
                                {
                                    location.LOCATIONGOODSID = int.Parse(locationGoodsId);
                                    n = nbl.UpdateLocationGoods(location);

                                    ActionInfo ai = new ActionInfo();
                                    if (location.STATUS == 0)
                                    {
                                        ai.OPERATIONNEW = "弃用";
                                    }
                                    else
                                    {
                                        ai.OPERATIONNEW = "启用";
                                    }
                                    BAction action = new BAction();

                                    ai.ACTIONTYPECODE = 1;
                                    ai.OPERATION = "修改";
                                    ai.OPCONTENT = "货位关联ID:" + location.LOCATIONGOODSID.ToString() + ",货位编号:" + location.LOCATIONCODE.ToString() + ",商品编号：" + goodsCode.ToString();
                                    ai.OPERATIONOLD = "";

                                    ai.USERCODE = model.USERCODE;
                                    action.AddLmActionInfo(ai);
                                }
                                else
                                {
                                    if (lt[0].WAREHOUSEID == 709)
                                    {
                                        sjson = "{success:false,msg:'" + goodsCode + "在" + warehouseName + "已存在正在使用货位！'}";
                                    }
                                    else if (lt[0].WAREHOUSEID == 712)
                                    {
                                        sjson = "{success:false,msg:'" + location.LOCATIONCODE + "货位已存在正在使用商品！'}";

                                    }
                                    else if (lt[0].WAREHOUSEID == 713)
                                    {
                                        sjson = "{success:false,msg:'" + location.LOCATIONCODE + "货位已存在正在使用商品！'}";

                                    }
                                }


                            }

                        }
                        else
                        {
                            sjson = "{success:false,msg:'" + goodsCode + "商品不存在！'}";
                        }
                    }
                    else
                    {
                        sjson = "{success:false,msg:'" + location.LOCATIONCODE + "货位不存在！'}";
                    }
                }

                if (n > 0)
                {
                    sjson = "{success:true}";
                }
                return sjson;


            }
            catch (Exception ex)
            {
                sjson = "{success:false,msg:'" + ex.Message + "'}";
            }
            return sjson;
        }



        [HttpPost]
        public FileResult ExportExcelLocationGoods(int page, int rows)//导出execl
        {
            //创建Excel文件的对象
            HSSFWorkbook book = new HSSFWorkbook();
            //添加一个sheet
            ISheet sheet1 = book.CreateSheet("Sheet1");
            #region 获取list数据
            int total = 0;
            string slocationCode = Request["txtSLOCATIONCODE"];
            string sgoodsCode = Request["txtSGOODSCODE"];
            string sgoodsName = Request["txtSGOODSNAME"];
            string valid = Request["valid"];
            
            string where = " where 1=1";
            if (!string.IsNullOrEmpty(slocationCode))
            {
                where += " and lo.LOCATIONCODE like'%" + slocationCode + "%'";
            }
            if (!string.IsNullOrEmpty(sgoodsCode))
            {
                where += " and g.GOODSCODE like'%" + sgoodsCode + "%'";
            }
            if (!string.IsNullOrEmpty(sgoodsName))
            {
                where += " and g.GOODSNAME like'%" + sgoodsName + "%'";
            }
            if (!string.IsNullOrEmpty(valid))
            {
                where += " and L.STATUS =" + valid + "";
            }

            BLocationGoods nc = new BLocationGoods();
            List<LocationGoods> list = nc.GetLocationGoodsList(page, int.MaxValue, out total, where);
            #endregion
            //给sheet1添加第一行的头部标题
            IRow row1 = sheet1.CreateRow(0);
            List<string> lstTitle = new List<string> { "货位编码", "商品编码", "商品名称", "仓库", "库位", "备注" };
            for (int i = 0; i < lstTitle.Count; i++)
            {
                row1.CreateCell(i).SetCellValue(lstTitle[i]);
            }
            //将数据逐步写入sheet1各个行
            for (int i = 0; i < list.Count; i++)
            {
                IRow rowtemp = sheet1.CreateRow(i + 1);
                rowtemp.CreateCell(0).SetCellValue(list[i].LOCATIONCODE);
                rowtemp.CreateCell(1).SetCellValue(list[i].GOODSCODE);
                rowtemp.CreateCell(2).SetCellValue(list[i].GOODSNAME);
                rowtemp.CreateCell(3).SetCellValue(list[i].WAREHOUSENAME);
                rowtemp.CreateCell(4).SetCellValue(list[i].CELLNO);
                rowtemp.CreateCell(5).SetCellValue(list[i].REMARK);
            }
            // 写入到客户端 
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            book.Write(ms);
            ms.Seek(0, SeekOrigin.Begin);
            return File(ms, "application/vnd.ms-excel", NewTimeStamp("LocationGoods"));
        }


        [HttpPost]
        public string ImportLocationGoods()
        {
            string sjson = string.Empty;
            try
            {

                HttpPostedFileBase file = Request.Files["files"];
                DataTable table = new DataTable();
                string importStr = string.Empty;
                sjson = ImportFile(file, out table, out importStr);
                if (!string.IsNullOrEmpty(sjson))
                    return sjson;

                TransactionOptions transactionOption = new TransactionOptions();

                //设置事务隔离级别
                transactionOption.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted;

                // 设置事务超时时间为600秒
                transactionOption.Timeout = new TimeSpan(0, 0, 600);

                //引用事务机制，出错时，事物回滚
                using (TransactionScope transaction = new TransactionScope(TransactionScopeOption.Required, transactionOption))
                {
                    try
                    {

                        for (int i = 0; i < table.Rows.Count; i++)
                        {
                            if (table.Rows[i][0] != null && table.Rows[i][0].ToString().Trim() != "")
                            {
                                string locationCode = table.Rows[i][0].ToString();
                                string goodsCode = table.Rows[i][1].ToString();

                                LocationGoods location = new LocationGoods();


                                sjson = CheckLocationGoods(locationCode, goodsCode, out location);
                                if (!string.IsNullOrEmpty(sjson))
                                    return sjson;
                                BLocationGoods nbl = new BLocationGoods();
                                int n = nbl.AddLocationGoods(location);
                            }
                        }
                        sjson = "{success:true}";
                        transaction.Complete();
                    }
                    catch (Exception ex)
                    {
                        sjson = "{success:false,msg:'" + ex.Message + "'}";
                        return sjson;
                    }
                }
            }
            catch (Exception ex)
            {
                sjson = "{success:false,msg:'" + ex.Message + "'}";
                return sjson;
            }

            System.Threading.Thread.Sleep(2000);
            return sjson;
        }

        private string CheckLocationGoods(string locationCode, string goodsCode, out LocationGoods location)
        {
            string sjson = string.Empty;
            string warehouseName = "";
            string where = " ";
            if (!string.IsNullOrEmpty(locationCode))
            {
                where += " and LOCATIONCODE ='" + locationCode + "'";
            }

            BLocationGoods nbl = new BLocationGoods();
            BLocationInfo li = new BLocationInfo();

            List<Location> lt = li.GetLocationCodeList("", where).ToList();
            List<Goods> goods = nbl.CheckGoodsInfo(goodsCode).ToList();
            AppUserList model = (AppUserList)Session["UserInfo"];

            location = new LocationGoods();
            location.LOCATIONCODE = locationCode;
            location.GOODSCODE = goodsCode;
            location.REMARK = "批量导入";
            location.STATUS = 1;
            location.CREATER = model.USERNAME;

            if (lt.Count > 0)//判断货位是否存在
            {
                if (goods.Count > 0)//判断商品是否存在
                {

                    location.LOCATIONID = lt[0].LOCATIONID;
                    location.GOODSID = goods[0].GOODSID;

                    string lgwhere = "";
                    if (lt[0].WAREHOUSEID == 709)//正常仓允许一个货位多个商品
                    {
                        if (goodsCode.IndexOf('W') > -1)
                        {
                            lgwhere = " where t1.STATUS=1 and  t1.goodsid=" + goods[0].GOODSID + " and t2.WAREHOUSEID=709 ";
                        }
                        else
                        {
                            lgwhere = " where t1.STATUS=1 and  t1.goodsid=" + goods[0].GOODSID;
                        }

                        warehouseName = "正常仓";
                    }
                    if (lt[0].WAREHOUSEID == 712)//分拣仓一对一
                    {
                        if (goodsCode.IndexOf('W') > -1)
                        {
                            warehouseName = "分拣仓";
                            lgwhere = " where t1.STATUS=1  and t1.LOCATIONID=" + lt[0].LOCATIONID;
                        }
                        else
                        {
                            sjson = "{success:false,msg:'非WOC商品只能放在正常仓'}";
                            return sjson;
                        }
                    }
                    if (lt[0].WAREHOUSEID == 818)//加工仓允许一个货位多个商品
                    {
                        if (goodsCode.IndexOf('W') > -1)
                        {
                            lgwhere = " where t1.STATUS=1 and  t1.goodsid=" + goods[0].GOODSID + " and t2.WAREHOUSEID=709 ";
                        }
                        else
                        {
                            lgwhere = " where t1.STATUS=1 and  t1.goodsid=" + goods[0].GOODSID;
                        }

                        warehouseName = "正常仓";
                    }
                    if (lt[0].WAREHOUSEID == 713)//摘果仓一对一
                    {
                        if (goodsCode.IndexOf('W') > -1)
                        {
                            warehouseName = "摘果仓";
                            lgwhere = " where t1.STATUS=1  and t1.LOCATIONID=" + lt[0].LOCATIONID;
                        }
                        else
                        {
                            sjson = "{success:false,msg:'非WOC商品只能放在正常仓'}";
                            return sjson;
                        }
                    }

                    List<LocationGoods> lg = nbl.GetLocationGoodsInfo(lgwhere).ToList();
                    if (lg.Count < 1)//是否满足关联条件
                    {
                        if (lt[0].WAREHOUSEID == 712)//如果是增加分拣仓关联
                        {
                            List<LocationGoods> lg1 = nbl.GetLocationGoodsInfo(" where  t1.STATUS=1 and t1.goodsid=" + goods[0].GOODSID + " and t2.WAREHOUSEID=712").ToList();
                            if (lg1.Count > 0)//判断商品是否在分拣仓存在
                            {
                                sjson = "{success:false,msg:'" + goodsCode + "在" + warehouseName + "已存在正在使用库位！'}";
                            }

                        }
                        if (lt[0].WAREHOUSEID == 713)//如果是增加摘果仓关联
                        {
                            List<LocationGoods> lg2 = nbl.GetLocationGoodsInfo(" where  t1.STATUS=1 and t1.goodsid=" + goods[0].GOODSID + " and t2.WAREHOUSEID=713").ToList();
                            if (lg2.Count > 0)//判断商品是否在摘果仓存在
                            {
                                sjson = "{success:false,msg:'" + goodsCode + "在" + warehouseName + "已存在正在使用库位！'}";
                            }

                        }
                    }
                    else
                    {
                        sjson = "{success:false,msg:'" + goodsCode + "在" + warehouseName + "已存在正在使用库位！或者" + locationCode.ToString() + "已绑定商品!'}";
                    }

                }
                else
                {
                    sjson = "{success:false,msg:'" + goodsCode + "商品不存在！'}";
                }

            }
            else
            {
                sjson = "{success:false,msg:'" + location.LOCATIONCODE + "货位不存在！'}";
            }
            return sjson;
        }
    }
}
